<?php
/**
 * KindEditor PHP
 *
 * 本PHP程序是演示程序，建议不要直接在实际项目中使用。
 * 如果您确定直接使用本程序，使用之前请仔细确认相关安全设置。
 *
 */
session_start();
require_once 'JSON.php';

$php_path = dirname(__FILE__) . '/';
$php_url = dirname($_SERVER['PHP_SELF']) . '/';

$app_root_path = realpath($php_path.'../../../').'/';
$upfile_config = require $app_root_path.'data/conf/upfile.php';

//根目录路径，可以指定绝对路径，比如 /var/www/attached/
//$root_path = $php_path . '../uploads/';
$root_path = str_replace("\\", '/', $upfile_config['up_path']);

//根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
//$root_url = $php_url . '../uploads/';

$info_config = require $app_root_path.'data/conf/info.php';
$root_url = $upfile_config['up_url'];

//判断截取长度
$use_path = substr($root_path,0,-2);
$length = strlen(realpath($use_path));// realpath兼容windows /home/wwwroot/... 在windows 可能是 E:/home/wwwroot/...
$use_url = substr($root_url,0,-2);

//图片扩展名
//$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
$ext_arr = explode(',', $upfile_config['up_exts']);

//目录名
$dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);

if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
    echo "Invalid Directory name.";
    exit;
}

if (!$_SESSION['uid'] && !$_SESSION['lessee_id']) {
    exit('please login system.');
}

//
if ($dir_name !== '' && $_SESSION['uid'] && $_GET['is_lessee'] != 1) {
    $root_path .= "/".$_SESSION['uid']. "/";
    $root_url  .= "/".$_SESSION['uid']. "/";

    if (!file_exists($root_path)) {
        mkdir($root_path, 0755, true);
    }
} elseif($dir_name !== '' && $_GET['is_lessee'] == 1 && $_SESSION['lessee_id']) {
    // 数据库连接
    $db_config = require_once(dirname(dirname(dirname(dirname(__FILE__)))).'/data/conf/db.php');

    $table_prefix = $db_config['DB_PREFIX'];

    $db_conn = mysqli_connect($db_config['DB_HOST'], $db_config['DB_USER'], $db_config['DB_PWD']);
    if (!$db_conn) {
      die('Failed to connect mysql server: ' . mysql_error());
    }
    mysqli_select_db($db_conn, $db_config['DB_NAME']) or die(mysqli_error($db_conn));

    // 数据表  
    $db = $table_prefix.'wxuser';

    $token = $_SESSION['token'];
    $sql = "SELECT uid FROM {$db} WHERE token = '{$token}'";
    $result = mysqli_fetch_assoc(mysqli_query($db_conn, $sql));

    $uid = $result['uid'];
    $root_path .= "/".$uid. "/wholesale/" .$_SESSION['lessee_id'] .'/';
    $root_url  .= "/".$uid. "/wholesale/" .$_SESSION['lessee_id'] .'/';
    if (!file_exists($root_path)) {
        mkdir($root_path, 0755, true);
    }
}

//根据path参数，设置各路径和URL 
if (empty($_GET['path'])) {
    $current_path = str_replace('\\', '/', realpath($root_path) . '/');
    $current_url = $root_url;
    $current_dir_path = '';
    $moveup_dir_path = '';
} else {
    $current_path = realpath($root_path) . '/' . $_GET['path'];
    $current_url = $root_url . $_GET['path'];
    $current_dir_path = $_GET['path'];
    $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
}
//echo realpath($root_path);
//排序形式，name or size or type
$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);

//不允许使用..移动到上一级目录
if (preg_match('/\.\./', $current_path)) {
    echo 'Access is not allowed.';
    exit;
}

//最后一个字符不是/
if (!preg_match('/\/$/', $current_path)) {
 echo 'Parameter is not valid.';
 exit;
}

//目录不存在或不是目录
if (!file_exists($current_path) || !is_dir($current_path)) {
    echo 'Directory does not exist.';
    exit;
}

//遍历目录取得文件信息
/* $file_list = array();
if (@$handle = opendir($current_path)) {
    $i = 0;
    while (false !== ($filename = readdir($handle))) {
        if ($filename{0} == '.') continue;
        $file = $current_path . $filename;
        if (is_dir($file)) {
            $file_list[$i]['is_dir'] = true; //是否文件夹
            $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
            $file_list[$i]['filesize'] = 0; //文件大小
            $file_list[$i]['is_photo'] = false; //是否图片
            $file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
        } else {
            $file_list[$i]['is_dir'] = false;
            $file_list[$i]['has_file'] = false;
            $file_list[$i]['filesize'] = filesize($file);
            $file_list[$i]['dir_path'] = '';
            $file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
            $file_list[$i]['filetype'] = $file_ext;
        }
        $file_list[$i]['filename'] = $filename; //文件名，包含扩展名
        $file_list[$i]['mtime'] = filemtime($file);
        $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file_list[$i]['mtime']); //文件最后修改时间
        $i++;
        if($i >= 10000) break;
    }
    closedir($handle);
} */

 //读取文件 
function my_scandir($dir,$length) { 
 static $file_list = array ();
 $path = $dir;
 if (@$handle = opendir($dir)) {
  $i = 0;
  while ( ($file = readdir ( $handle )) !== false ) {
   if ($file{0} == '.') continue; 
   if ($file != ".." && $file != ".") {
   if (is_dir ( $dir . "/" . $file )) {
       // 不读取wholesale文件夹
       if ($file === 'wholesale') continue;
        $path .='/'.$file;
        $url  .='/'.$file;
        my_scandir ( $dir . "/" . $file,$length);
    } else {
        $file_list[$i]['path'] = $path."/".$file;
        $file_list[$i]['filename'] = substr($path."/".$file,$length);
        $file_list[$i]['is_dir'] = false;
        $file_list[$i]['has_file'] = false;
        $file_list[$i]['filesize'] = filesize($file_list[$i]['path']);
        $file_list[$i]['mtime'] = filemtime($file_list[$i]['path']);
        $file_list[$i]['datetime'] = date('Y-m-d H:i:s', $file_list[$i]['mtime']); //文件最后修改时间
        $file_list[$i]['is_photo'] = pathinfo($file_list[$i]['filename'],PATHINFO_EXTENSION);
        $file_list[$i]['filetype'] = $file_list[$i]['is_photo'];
    }
   }
   $i++;
   if($i >= 10000) break;
  }
  closedir ( $handle );
  return $file_list;
 }
}

$current_path = substr($current_path,0,-1);
$file_list_v2 = my_scandir($current_path,$length);
$current_path_v1 = str_replace('v2', 'v1', $current_path);
$file_list_v1 = my_scandir($current_path_v1,$length);
if(empty($file_list_v1) && empty($file_list_v2)) {
    $file_list = array();
} else {
    if(empty($file_list_v1)) {
        $file_list_v1 = array();
    } elseif(empty($file_list_v2)) {
        $file_list_v2 = array();
    }
    $file_list = array_merge($file_list_v1,$file_list_v2);
}

//排序 
function cmp_func($a, $b) {
    global $order;
    if ($a['is_dir'] && !$b['is_dir']) {
        return -1;
    } else if (!$a['is_dir'] && $b['is_dir']) {
        return 1;
    } else {
        if ($order == 'size') {
            if ($a['filesize'] > $b['filesize']) {
                return 1;
            } else if ($a['filesize'] < $b['filesize']) {
                return -1;
            } else {
                return 0;
            }
        } else if ($order == 'type') {
            return strcmp($a['filetype'], $b['filetype']);
        } else if ($order == 'mtime') {
            //时间反序
            if($a['mtime'] > $b['mtime']) return 0;
            return ($a['mtime'] < $b['mtime']) ? 1 : -1;
        } else {
            return strcmp($a['filename'], $b['filename']);
        }
    }
}

usort($file_list, 'cmp_func');

$result = array();
//相对于根目录的上一级目录
$result['moveup_dir_path'] = $moveup_dir_path;
//相对于根目录的当前目录
$result['current_dir_path'] = $current_dir_path;
//当前绝对路径
$result['current_path'] = $use_path;
//当前目录的URL
$result['current_url'] = $use_url;
//文件数
$result['total_count'] = count($file_list);
//文件列表数组
$result['file_list'] = $file_list;
 
//输出JSON字符串   
header('Content-type: application/json; charset=UTF-8');
$json = new Services_JSON();
echo $json->encode($result);
